package com.csyaonie.android;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import com.csyaonie.android.utils.ToastUtil;

public class HandlerActivity extends AppCompatActivity {

    private Button bt_handler1;
    private Button bt_handler2;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        bt_handler1=findViewById(R.id.bt_handler1);
        bt_handler2=findViewById(R.id.bt_handler2);
        mHandler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        ToastUtil.show(HandlerActivity.this,"线程通信成功");
                        break;
                }
            }
        };

        bt_handler1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Handler handler=new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.show(HandlerActivity.this,"延时执行成功");
                    }
                },3000);
            }
        });

        bt_handler2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){
                    @Override
                    public void run() {
                        Message msg=new Message();
                        msg.what=1;
                        mHandler.sendMessage(msg);
                    }
                }.start();
            }
        });
    }
}